<?php
// +----------------------------------------------------------------------
// | Ntalker插件安装程序 UCHome                                                             
// +----------------------------------------------------------------------
// | Copyright (c) 2010 http://www.ntalker.com All rights reserved.      
// +----------------------------------------------------------------------
// | Author: lsh
// | Latest Update:    2010-10-18                                 
// +----------------------------------------------------------------------
    @session_start();
    error_reporting(7);
    @set_time_limit(1000);
    if(!$_SESSION['installid']){
         $ins_start = true;
         $_SESSION['installid'] = date('Ymdhms',time());
    }else{
         $ins_start = false;
    }
    if(isset($_GET['newversion'])){
         $_SESSION['topversion'] = trim($_GET['newversion']);
         $_SESSION['issupport'] = trim($_GET['newissupport']);
    } 
    
    imshow_header();

    define('IN_UCHOME', TRUE);
    define('IN_NTALKER', TRUE);
    define('SELF_FILE', $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME']);
    define('INSTALLROOT', dirname(__FILE__).'/');
    define('SITEROOT', $_SERVER['DOCUMENT_ROOT'].'/');

    $recordurl = 'http://www.ntalker.com/autoopen.php';

    //获取安装包中网站信息
    if( file_exists(INSTALLROOT.'./configs.php')){
         $cfgarr  = @include(INSTALLROOT.'./configs.php');
         $im_siteid        = $cfgarr[0];
         $im_enablesitekey = $cfgarr[1];
         $im_sitekey       = $cfgarr[2];
         $im_domainurl     = 'http://'.$cfgarr[3];
    }else{
         $im_siteid        = "ntalkerdemo";
         $im_enablesitekey = "0";
         $im_sitekey       = "";
         $im_domainurl     = "";
    }
    //开通服务验证key
    $insauthkey = md5($im_siteid.'_'.$im_sitekey);
    $errormsg = $installSQL = '';
    $pluginCfg = $insdb = $insfilelist = $clsreg = $_config = $crossdomain = array();
    
    //发送卸载程序开始
    if($ins_start){
         $jsonparm = '{sessionid:"'.$_SESSION['installid'].'",siteid:"'.$im_siteid.'",action:"record",record:"uninstall:start"}';
         interact($jsonparm);
    }
    
    //1-检查安装包运行所需文件
    $insfiles = array('./ntalker_config.php','./ntalker.inc.php');
    foreach($insfiles AS $insfile){
         if(file_exists(INSTALLROOT.$insfile)){
              @include_once (INSTALLROOT.$insfile);
         }else{
              $errormsg = $errormsg ? $errormsg.$insfile.' <br />' : $insfile.' <br />';
              $errordesc = 'install_run_needfile_absence';
         }
    }
    if($errormsg){
         $jsonparm = '{sessionid:"'.$_SESSION['installid'].'",siteid:"'.$im_siteid.'",action:"record",record:"precheck",desc:"'.$errordesc.'"}';
         interact($jsonparm);
         $dealmsg ='步骤1：删除服务器上的ntalker安装文件夹。<br />步骤2：登陆站长管理中心下载安装包（进入站长管理中心：<a href="http://site.ntalker.com">site.ntalker.com</a>）<br />
                    步骤3：解压安装包并把ntalker文件夹上传到UCHome目录，且确认所有文件上传完毕。<br />步骤4：在浏览器里重新运行安装程序。';
         imshow_msg('问题：安装包不完整，缺少安装文件：',$errormsg,$dealmsg,false,false);
    }
    
     //2-检查论坛目录 
     if(!defined('Uchome_ROOT')){
         // 首先检查安装目录是否为论坛目录
         if(file_exists(INSTALLROOT.'./config.php')){
              define('Uchome_ROOT', INSTALLROOT);
              //如果安装目录即为论坛目录，则在data目录下建立ntalker目录，保存安装后的ntalker文件
              if(!is_dir(Uchome_ROOT.'./data/ntalker')) {
                  @mkdir(Uchome_ROOT.'./data/ntalker', 0777);
              }
              define('NTALKER_DATA_ROOT',Uchome_ROOT.'./data/ntalker/');
         }else{
              $inslenth = check_bbsdir();
              if($inslenth==-1){
                   //检查到网站目录还没有找到论坛数据库配置文件，则提示错误
                   $errormsg = '步骤1：请将Ntalker安装文件夹移动到uchome目录下，重新安装。<br />步骤2：确认网站软件类型为UCHome，如果不符，登陆站长管理中心下载安装包（进入站长管理中心：<a href="http://site.ntalker.com">site.ntalker.com</a>）';
                   $errordesc = 'site_root_invalid';
                   
                   $jsonparm = '{sessionid:"'.$_SESSION['installid'].'",siteid:"'.$im_siteid.'",action:"record",record:"precheck",desc:"'.$errordesc.'"}';
                   interact($jsonparm);
                   imshow_msg('问题：无法找到安装所需的UCHome文件。','',$errormsg);
              }
        }
    }

    //加载论坛配置文件
    if(file_exists(Uchome_ROOT.'./config.php')){
          if(!file_exists(Uchome_ROOT.'./ver.php')){
               @include(Uchome_ROOT.'./common.php');
          }else{
               @include(Uchome_ROOT.'./config.php'); 
               @include(Uchome_ROOT.'./ver.php');
               @include(Uchome_ROOT.'./source/function_common.php');
          }
          define('INSCHARSET',strtolower($_SC['charset']));             
    }
    global $_config,$clsreg,$crossdomain,$installSQL,$insfilelist,$pluginCfg,$insdb,$insauthkey;
    InitGP(array('error','action','type','instemplate','sid','tpl'));
    
    //4-获取网站域名和字符集
    if(!defined("INSSITEURL")){    
         $install_lenth = strlen(str_replace('\\','/',INSTALLROOT))-strlen(str_replace('\\','/',Uchome_ROOT));
         $insbbsurl = htmlspecialchars( 'http://'.$_SERVER['HTTP_HOST'].substr(SELF_FILE, 0, strrpos(SELF_FILE, '/')-$install_lenth));
         define('INSSITEURL',$insbbsurl);
    }
    //安装目录对于论坛目录的相对路径
    define('SHOW_INS_ROOT',str_replace(str_replace('\\','/',Uchome_ROOT),'./',str_replace('\\','/',INSTALLROOT)));
    $sub_dir = str_replace(str_replace('\\','/',Uchome_ROOT),'',str_replace('\\','/',INSTALLROOT));
    $sub_dir = substr(INSSITEURL,-1,1)=='/' ? $sub_dir : '/'.$sub_dir;
    $sub_dir = substr($sub_dir,-1,1)=='/' ? $sub_dir : $sub_dir.'/';
    define('SHOW_INS_SITEURL',$sub_dir);

    //5-判断是否安装锁定
    if(inschecklock()){
          $errormsg = '请登录网站服务器，删除UCHome目录下 '.SHOW_INS_ROOT.'install.lock 文件，再点击【重新检查】。';
          $errordesc = 'install_locked';
          $jsonparm = '{sessionid:"'.$_SESSION['installid'].'",siteid:"'.$im_siteid.'",action:"record",record:"precheck",desc:"'.$errordesc.'"}';
          interact($jsonparm);
          imshow_msg('问题：检测到安装保护文件。','',$errormsg,false,true);
    }

    //6-判断是否有版本配置文件
    $configfilename = './install/'.INSCHARSET.'/config_'.X_VER.'.php';
    if(inscheckversion($configfilename)){
          $insfilelist = @include(INSTALLROOT.$configfilename);
    }else{
          $configfilename = './ntalkerdata/config_'.X_VER.'.php';
          if(inscheckversion($configfilename)){
               $insfilelist = @include(INSTALLROOT.$configfilename);
          }else{
               $errormsg = '请重新上传安装文件或联系安装支持了解Ntalker安装包是否支持该版本UCHome。';
               $errordesc = 'install_config_file_absence2';
               $jsonparm = '{sessionid:"'.$_SESSION['installid'].'",siteid:"'.$im_siteid.'",action:"record",record:"precheck",desc:"'.$errordesc.'"}';
               interact($jsonparm);
               imshow_msg('问题：缺少配置文件：',$configfilename,$errormsg);
          }
    }

    switch($action){
        case "checkperm":  //权限检测
    ?>
        <div class="topnav" >检测卸载文件权限</div>
        <div class="cont">
        <div class="c_bj1"></div>
        <div class="c_bj2" style="overflow:auto;">
        <table width="76%" border="0" align="center" cellpadding="0" cellspacing="0">
            <tr class="f_blod">
              <td width="58%" height="30">项目</td>
              <td width="20%">所需配置</td>
              <td width="22%">当前配置</td>
            </tr>
            <tr>
              <td height="30">PHP版本</td>
              <td>PHP4.0以上</td>
              <td><img src="install/images/ok.gif" width="16" height="14" /><?php echo(PHP_VERSION); ?></td>
            </tr>
            <tr>
              <td height="30">网站软件版本</td>
              <td>1.5-2.0</td>
              <td><img src="install/images/ok.gif" width="16" height="14" /><?php echo(X_VER); ?></td>
            </tr>
          </table>
          <table width="76%" border="0" align="center" cellpadding="0" cellspacing="0">
            <tr class="f_blod">
              <td height="30">目录 文件权限检查</td>
              <td>&nbsp;</td>
              <td>&nbsp;</td>
            </tr>
            <tr class="f_blod">
              <td width="58%" height="30">目录文件</td>
              <td width="20%">所需状态</td>
              <td width="22%">当前状态</td>
            </tr>
        <?php
           $tplid = $tpl ? implode(',', $tpl) : '';
           $state = inscheckperm($type,$tplid); 
           if($state) {
                $retry = 'disabled="disabled" style="display:none"';
                $jsonparm = '{sessionid:"'.$_SESSION['installid'].'",siteid:"'.$im_siteid.'",action:"record",record:"uninstall:checkperm:finish"}';
                interact($jsonparm);
           }else{
                $successd = 'disabled="disabled" style="display:none"';
           }
        ?>
		</table>        
        </div>
        <div class="c_bj3"></div>        
        <div class="bu">
            <INPUT TYPE="button"  class="but_"  VALUE="重新检查" <?php echo $retry;?> onclick="window.location.href='<?php echo(SELF_FILE);?>?action=checkperm&type=uninstall'" />
            <INPUT TYPE="button"  class="but_"  VALUE="下一步" <?php echo($successd);?> onclick="window.location.href='<?php echo(SELF_FILE);?>?action=uninstall'" />
        </div></div>
<script language="javascript" type="text/javascript">
 var checkstat = '<?php echo $retry;?>';
 if(!checkstat) {
       var errorperm = document.getElementsByName("checkperm");
       var errorvalue = '';
       for(var i=0; i<errorperm.length; i++)
        {
             errorvalue = errorvalue ? errorvalue + ":" + errorperm[i].value : errorperm[i].value;
        }
       createScript("<?php echo($recordurl);?>",{action: "record",record: "uninstall:checkperm",sessionid: "<?php echo ($_SESSION['installid']);?>",siteid: "<?php echo ($im_siteid);?>",desc:  errorvalue}); 
 }      
</script>
	<?php  break;
	    case "uninstall":  //卸载
    ?>
        <div class="topnav" >卸载Ntalker</div>
        <div class="cont">
        <div class="c_bj1"></div>
        <div class="c_bj2">
		<?php
			if(!checkInstall()){
                exit('<script language="javascript">window.location.href=\''.INSSITEURL.SHOW_INS_SITEURL.'install/index.php'.'\';</script>');
            }else{
                  if(uninstall()){
                       $retry = 'disabled="disabled" style="display:none"';
                       $jsonparm = '{sessionid:"'.$_SESSION['installid'].'",siteid:"'.$im_siteid.'",action:"record",record:"uninstall:finish"}';
                       interact($jsonparm);
                  }
            }
		?>			
		</div>
		<div class="c_bj3"></div>
        <div class="bu">
            <INPUT type="button"  class="but_"  name="btnclear" value="重试" <?php echo $retry;?> onclick="window.location.href='<?php echo(SELF_FILE);?>';" />
			<INPUT type="button"  class="but_"  value="退出" onclick="window.location.href='<?php echo(INSSITEURL);?>';" />
		</div></div>
<script language="javascript" type="text/javascript">
 var uninstallkstat = '<?php echo $retry;?>';
 if(!uninstallkstat) {
       var uninstallmsg = document.getElementsByName("uninstallmsg");
       var uninstallvalue = '';
       for(var i=0; i<uninstallmsg.length; i++)
        {
             uninstallvalue = uninstallvalue ? uninstallvalue + ":" + uninstallmsg[i].value : uninstallmsg[i].value;
        }
       createScript("<?php echo($recordurl);?>",{action: "record",record: "uninstall:uninstall",sessionid: "<?php echo ($_SESSION['installid']);?>",siteid: "<?php echo ($im_siteid);?>",desc:  uninstallvalue}); 
 }      
</script>
    <?php    break;
        case "postreason":    //卸载原因
    ?>
     <form name="Form" METHOD="POST" action="<?php echo(SELF_FILE);?>">
        <INPUT type="hidden" name="action" value="<?php echo($ntaction);?>" />
        <div class="topnav" >卸载Ntalker的原因</div>
        <div class="cont">
        <div class="c_bj1"></div>
        <div class="c_bj2">
            <span class="f14_">
            <input type="hidden" name="siteid" id="siteid" value="<?php echo $im_siteid?>" />
            <input type="hidden" name="url" id="url" value="<?php echo urlencode(INSSITEURL)?>" />
        <?php
            $reason_a = array(1=>'网站更新',3=>'升级Ntalker',4=>'加载速度慢',5=>'广告太多',6=>'定制项目较少',7=>'与网站原有功能冲突');
            $reason_b = array_rand($reason_a,6);
            $reason_key = $reason_value = array();
            foreach($reason_b as $_valve){
                 $reason_value[] = $reason_a[$_valve];
                 $reason_key[] = $_valve;
            }
        ?>
            <input type="checkbox" name="reason" value="<?php echo $reason_key[0];?>" />1. <?php echo $reason_value[0];?><br />   
            <input type="checkbox" name="reason" value="<?php echo $reason_key[1];?>" id="reason" />2. <?php echo $reason_value[1];?><br />
            <input type="checkbox" name="reason" value="<?php echo $reason_key[2];?>" id="reason" />3. <?php echo $reason_value[2];?><br />
            <input type="checkbox" name="reason" value="<?php echo $reason_key[3];?>" />4. <?php echo $reason_value[3];?><br />
            <input type="checkbox" name="reason" value="<?php echo $reason_key[4];?>" />5. <?php echo $reason_value[4];?> <br />
            <input type="checkbox" name="reason" value="<?php echo $reason_key[5];?>" />6. <?php echo $reason_value[5];?> <br />
            <input type="checkbox" name="reason" value="8" />7. 其他意见（400个字符以内），请填写：</span><br />
            <textarea name="customize" onchange="changetext(this)" style="width:400px;height:50px;" id="customize"></textarea>
        </div> 
        <div class="c_bj3"></div>        
        <div class="bu">    
            <input type="button" class="but_" onclick=nextbtn() value="确定提交" />
        </div></div>
   </form>  
   <script language="javascript">
       function nextbtn()
    {
        var value='';
        var items     = document.getElementsByName("reason");
        var customize = document.getElementById("customize").value;
        var siteid    = document.getElementById("siteid").value;
        var url       = document.getElementById("url").value;
        for(var i=0; i<items.length; i++)
        {
            if( items[i].type=="checkbox" && items[i].checked){
                if(items[i].value=="8" && customize==''){
                    alert("请填写卸载Ntalker的原因！");
                    return;
                }
                value += items[i].value + ",";
            }
        }
        if(value==''){
            alert('请选择或者填写卸载Ntalker的原因！');
            return;
        }
        if(document.getElementById("customize").value.length>400){
            alert("此文本框最多输入400个字符！");
            return;
        }
        var submiturl = 'http://www.ntalker.com/autoopen.php';
        var jsparm = 'reason=' + value + '&siteid=' + siteid + '&url=' + url + '&returntype=1';
        if(customize) jsparm += '&customize='+encodeURIComponent(customize);
        createScript(submiturl,jsparm,function(){window.location.href='<?php echo(SELF_FILE);?>?action=checkperm&type=uninstall'});
    }
    function changetext(obj)
{
    var value = document.getElementById("customize").value;
    if(value.length>400){
        alert("此文本框最多输入400个字符！");
    }
}
   </script>
	<?php	break;
	    default : //判断是否未安装
    ?>
	    <div class="topnav" >卸载Ntalker的原因</div>
        <div class="cont">
        <div class="c_bj1"></div>
        <div class="c_bj2">
        <?php
            if(!checkInstall()){
                 echo ('您尚未安装Ntalker，不能进行卸载操作！');
                 $jsonparm = '{sessionid:"'.$_SESSION['installid'].'",siteid:"'.$im_siteid.'",action:"record",record:"uninstall:notinstall"}';
                 interact($jsonparm);
            }else{
                 echo ('<script language="javascript">window.location.href=\''.SELF_FILE.'?action=postreason'.'\';</script>');
            }
        ?>
        </div>            
        <div class="c_bj3"></div>        
        <div class="bu">
            <INPUT type="button"  class="but_"  value="退  出" onclick="window.location.href='<?php echo(INSSITEURL);?>';" />
        </div>
<?php
		break;
}
    imshow_footer(); 

   function imshow_header(){
        print <<<EOF
        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
        <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Ntalker插件安装包 For UCHome </title>
        <link rel="stylesheet" media="screen" href="install/css/style_index.css" />
        <link rel="stylesheet" media="screen" href="install/css/base.css" />
        <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />
        </head>
        <body>
        <div  id="container">
        <!--头部-->
        <div class="top">
          <div class="logo"></div><div class="top_right">技术支持：010-64419266-8011<br />Ntalker V3.0 For UCHome版</div>
        </div>
         <script language="javascript">
            if(document.getElementById('msgDiv'))
            {
                document.getElementById('msgDiv').scrollTop=document.getElementById('msgDiv').scrollHeight;
            }
         </script>
         <script language="javascript" type="text/javascript">   
            function $\$O(id){
                return document.getElementById(id)||null;
            };
            function createScript(url, jsonpram, callback){
                var src, strPram = [];
                switch( typeof(jsonpram) ){
                       case 'undefined': return;break;
                       case 'string': 
                           src = url + '?' + jsonpram;
                           break;
                       case 'object':
                           for(var k in jsonpram){
                              if( typeof(jsonpram[k]) == 'string' ){
                                     strPram.push(k + '=' + jsonpram[k]);
                                  }
                           }
                           src = url + '?' + strPram.join('&');
                          break;
                }
                var head = document.getElementsByTagName("HEAD")[0], 
                    elem = document.createElement("SCRIPT"), 
                    done = false;
                elem.setAttribute('language', 'javascript');
                elem.setAttribute('type', 'text/javascript');
                elem.setAttribute('charset', 'utf-8');
                elem.setAttribute('src',src);
                elem.onload = elem.onreadystatechange = elem.onerror = function(){
                    if ( !done && ( !this.readyState || /loaded|complete/.test(this.readyState) ) ) {
                        done = true;
                        if( typeof(callback) == "function" ) callback();
                    }
                };
                head.appendChild(elem);
                return elem;
            }
         </script>
EOF;
   }
   function imshow_footer($quit=true){
        print <<<EOF
        <div class="bot">能通天下版权所有 京ICP证:080695号 Copyright 2010 Ntalker.com. All Rights Reserved</div>
        </div>
        </body>
        </html>
EOF;
   $quit && exit();
   }
   function interact($jsonparms,$callback=''){
        global $recordurl;
        echo '<script language="javascript" type="text/javascript">';
        echo 'createScript("'.$recordurl.'",';
        echo $jsonparms;
        if($callback){
             echo','.$callback.');';
        }else{
             echo ');';
        }
        echo '</script><br />';
   }
   function imshow_msg($errtitle,$addmsg='',$dealmsg,$iscontinue=false,$isrecheck=false){
        global $pluginCfg;
        echo '<div class="topnav" style="text-align:left;">错 误 提 示</div>
              <div class="cont" style="height:400px;">';   
        echo '<p class="f14 f12_orange f_blod">'.$errtitle.'</p>';
        if($addmsg){
             echo '<p>'.$addmsg.'</p>';
        }
        echo '<p class="f14 f_blod">解决办法</p>';
        echo '<p>'.$dealmsg.'</p>';
        echo '<p>问题仍无法解决？联系Ntalker技术支持（邮箱：<a href="mailto:ntalker@ntalker.com"><span class="f_blue">ntalker@ntalker.com</span></a>，电话：010-64419266-8011）</p>';
        if($iscontinue){
             echo '</div><div class="bu2">';
        }else{
             echo '</div><div class="bu">';
        }
        if($iscontinue){
             echo '<INPUT type="button" class="but_" value="继续安装" onclick="window.location.href=\''.SELF_FILE.'?newversion='.$pluginCfg['version'][X_VER].'\';" />';
        }
        if($isrecheck){
             echo '<INPUT type="button" class="but_" value="重新检查" onclick="window.location.href=\''.SELF_FILE.'\';" />';
        }else{
             echo '<INPUT TYPE="button" class="but_" value="退  出" onclick="window.location.href=\''.INSSITEURL.'\';" />';
        }
        echo '</div>';
        imshow_footer();
   }
?>